<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>销售账单</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="pageContentWhole">
      <a-form layout="inline" :model="form" style="margin-top:0px;">
        <a-form-item label="客户名称">
          <a-input v-model="form.custName" />
        </a-form-item>
        <a-form-item label="所属部门">
          <a-tree-select
            class="selectInputWidth"
            v-model="form.deptId"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :load-data="onLoadData"
            :tree-data="deptTreeData"
            placeholder="请选择"
            @change="onChangeTree"
          ></a-tree-select>
        </a-form-item>
        <a-form-item label="所属销售">
          <a-select v-model="form.sellerId" class="selectInputWidth">
            <a-select-option value>全部</a-select-option>
            <a-select-option v-for="v in sellers" :key="v.uiId">{{v.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="对账日期">
          <a-range-picker @change="timeChange" :value="timeValue" style="width:250px">
            <a-icon slot="suffixIcon" type="calendar" />
          </a-range-picker>
        </a-form-item>
        <a-form-item label="收货人">
          <a-input v-model="form.consignee" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="check">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="excelExport">批量下载账单</a-button>
        </a-form-item>
      </a-form>
      <a-table
        :columns="columns"
        :loading="loading"
        :data-source="data"
        :row-selection="rowSelection"
        style="margin-top:25px;"
        :pagination="pagination"
        :scroll="{x:1500}"
        :row-key="(record,index) => index"
      >
        <span slot="action" slot-scope="record" :style="'display: flex; align-items: center;'">
          <a @click="download(record)" style="margin-right:10px">下载</a>
          <a @click="detail(record)">查看</a>
        </span>
      </a-table>
    </div>
  </div>
</template>
<script>
import { querySellerDown, queryDeptDown } from '@/api'
import { commonExport } from '@/api/request'
import { queryCustomerBillList } from '@/api/salesCenter'
const deptData = {
  type: 1, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL'
}
const sellerData = {
  type: 1, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL',
  status: 1
}
const columns = [
  {
    title: '序号',
    width: 80,
    customRender: (text, record, index) => {
      return index + 1
    }
  },
  {
    title: '对账单编号',
    dataIndex: 'billCode'
  },
  {
    title: '客户名称',
    dataIndex: 'custName'
  },
  {
    title: '收货人',
    dataIndex: 'consignee'
  },
  {
    title: '所属销售',
    dataIndex: 'sellerName'
  },
  {
    title: '所属部门',
    dataIndex: 'department'
  },
  {
    title: '账单金额',
    dataIndex: 'amount'
  },
  {
    title: '对账日期',
    dataIndex: 'createTime'
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action'
    }
  }
]
export default {
  data () {
    return {
      isFirstEnd: true,
      deptTreeData: [],
      sellers: [],
      form: {
        deptId: '',
        sellerId: '',
        queryStartTime: '',
        queryEndTime: '',
        custName: '',
        consignee: ''
      },
      columns,
      loading: true,
      data: [],
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      timeValue: [],
      selectedRowKeys: [],
      selectedIdList: []
    }
  },
  computed: {
    rowSelection () {
      const { selectedRowKeys } = this
      return {
        selectedRowKeys,
        onChange: this.onSelectChange,
        type: 'checkbox',
        selections: []
      }
    }
  },
  methods: {
    onLoadData (treeNode) {
      return new Promise((resolve) => {
        if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
          resolve()
          return
        }
        queryDeptDown({ parentId: treeNode.dataRef.key, ...deptData }).then(
          (rsp) => {
            let childrenData = []
            rsp.data.forEach((value) => {
              childrenData.push({
                title: value.name,
                key: value.deptId,
                value: value.deptId
              })
            })
            treeNode.dataRef.children = childrenData
            this.deptTreeData = [...this.deptTreeData]
            resolve()
          }
        )
      })
    },
    initDept (e) {
      return new Promise((resolve) => {
        queryDeptDown(e).then((rsp) => {
          let initData = []
          rsp.data.forEach((value, index) => {
            initData.push({
              title: value.name,
              key: value.deptId,
              value: value.deptId
            })
          })
          this.deptTreeData = initData
          this.form.deptId = rsp.data[0].deptId
          if (this.isFirstEnd) {
            resolve(this.form.deptId)
          }
        })
      })
    },
    onChangeTree (value) {
      this.initSellerDown(value)
    },
    initSellerDown (deptId) {
      return new Promise((resolve) => {
        querySellerDown({ ...sellerData, deptId }).then((rsp) => {
          this.sellers = rsp.data.map((v, i) => {
            if (!v.uiId) {
              v.name = '请选择'
              v.uiId = ''
            }
            return v
          })
          this.form.sellerId = rsp.data[0].uiId
          if (this.isFirstEnd) {
            resolve(this.form.sellerId)
          }
        })
      })
    },
    custPackingListRequest (e) {
      this.loading = true
      queryCustomerBillList(e).then(res => {
        this.isFirstEnd = false
        this.data = res.data.list
        this.selectedRowKeys = []
        let currentPage = this.pageNum
        this.pagination = {
          current: currentPage,
          pageSize: res.data.pageSize,
          total: res.data.total,
          showQuickJumper: false,
          showSizeChanger: true,
          showTotal: (total) =>
            `共${total}条记录 第${currentPage}/${res.data.pages}页`,
          onChange: (pageNum) => {
            this.pageNum = pageNum
            let paramData = {
              ...this.form,
              pageSize: this.pageSize,
              pageNum: this.pageNum
            }
            this.custPackingListRequest(paramData)
          },
          onShowSizeChange: (current, size) => {
            this.pageNum = current
            this.pageSize = size
            let paramData = {
              ...this.form,
              pageSize: this.pageSize,
              pageNum: this.pageNum
            }
            this.custPackingListRequest(paramData)
          }
        }
        setTimeout(() => {
          this.loading = false
        }, 300)
      })
    },
    timeChange (date, dateStr) {
      this.timeValue = date
      this.form.queryStartTime = dateStr[0]
      this.form.queryEndTime = dateStr[1]
    },
    onSelectChange (record, selected, selectedRows, nativeEvent) {
      // console.log(record)
      // console.log(selected)
      this.selectedRowKeys = record
      let selectedIdList = []
      selected.forEach(v => {
        selectedIdList.push(v.id)
      })
      // console.log(selectedIdList)
      this.selectedIdList = selectedIdList
    },
    download (e) {
      let billId = e.id
      let exportParam = {
        'feeType': 1,
        'billId': billId
      }
      commonExport('/bill/exportBillCostList', exportParam)
    },
    detail (e) {
      window.open(`/financialCenter/receivableBillOfHuaJzx/${e.id}`, '_blank')
    },
    check () {
      this.pageNum = 1
      this.custPackingListRequest({
        ...this.form,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
    },
    excelExport () {
      if (this.selectedIdList.length === 0) {
        this.$message.error('请勾选一条进行批量下载')
        return false
      }
      commonExport('/bill/exportCustomerBillBatch', {
        billIds: this.selectedIdList,
        fileType: 'zip'
      })
    }
  },
  mounted () {
    Promise.all([this.initDept(deptData), this.initSellerDown()]).then(
      (result) => {
        this.custPackingListRequest({
          deptId: result[0],
          sellerId: result[1],
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
      }
    )
  }
}
</script>
